import time
import requests
import execjs
from QiangZhi.VerCode import VerCode as vc
from bs4 import BeautifulSoup
import json

from course.model import Classtable
from course.model import db


class JiaoWu:
    def __init__(self, username, password, school):
        self.user_name = username
        self.password = password

    session = requests.session()  # 全局请求对象

    cookie = ''
    data_str = ''
    encode_str = ''

    def login_init(self):  # 初始化登录，加载cookie
        header = {
            "Content-Type": "text/html;charset=utf-8",
            "Vary": "Accept-Encoding"
        }
        url_main = "http://scauzhujiangjw.minghuaetc.com/hnnydxzjxy/Logon.do?method=logon&flag=sess"
        response = self.session.get(url_main, headers=header)
        self.data_str = response.text
        self.cookie = self.session.cookies.get_dict()['JSESSIONID']
        return self.cookie

    def download_ver_code(self):
        url_ver_code = 'http://scauzhujiangjw.minghuaetc.com/hnnydxzjxy/verifycode.servlet'
        cookie = {"Cookie": self.cookie}
        response = self.session.get(url_ver_code)
        img = response.content
        return img

    def login(self):
        code = vc.verifycode()
        ver_code = code.crack(self.download_ver_code())
        login_post_header = {
            "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
            "Accept-Encoding": "gzip, deflate",
            "Accept-Language": "zh-CN,zh;q=0.9",
            "Cache-Control": "max-age=0",
            "Content-Length": "116",
            "Content-Type": "application/x-www-form-urlencoded",  # 接收类型
            "Cookie": 'JSESSIONID=' + self.cookie,
            "Host": "scauzhujiangjw.minghuaetc.com",
            "Origin": "http://scauzhujiangjw.minghuaetc.com",
            "Proxy-Connection": "keep-alive",
            "Referer": "http://scauzhujiangjw.minghuaetc.com/hnnydxzjxy/",
            "Upgrade-Insecure-Requests": "1",
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) "
                          "Chrome/88.0.4324.190 Safari/537.36"
        }

        self.encode_str = self.encode()

        login_postData = {
            'view': '1',
            'useDogCode': '',
            'encoded': self.encode_str,  # 账号密码加密后的东西
            'RANDOMCODE': ver_code
        }

        login_url = 'http://scauzhujiangjw.minghuaetc.com/hnnydxzjxy/Logon.do?method=logon'
        msg = self.session.post(
            login_url, headers=login_post_header, data=login_postData)
        txt = msg.text
        if txt.find('个人中心') > 0:
            soup = BeautifulSoup(txt, 'lxml')
            info = soup.find('div', id='Top1_divLoginName')
            return '登录成功！\n' + info.text
        elif txt.find('验证码错误') > 0:
            return '验证码错误'
        elif txt.find('该帐号不存在或密码错误') > 0:
            return '账号或者密码错误'
        else:
            return '未知错误'

    def parse_page(self, week):
        d = ''
        with open('admin/scauzj.txt', 'r', encoding='utf-8')as f:
            d = f.read()
            f.close()

        post_data = {
            'zc': week,  # 周次
            'xnxq01id': d,  # 学期
            'sfFd': '1'  # 放大
        }
        header = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) '
                          'Chrome/88.0.4324.190 Safari/537.36',
            'Host': 'scauzhujiangjw.minghuaetc.com',
            'Referer': 'http://scauzhujiangjw.minghuaetc.com/jsxsd'
        }

        response = self.session.post(
            'http://scauzhujiangjw.minghuaetc.com/hnnydxzjxy_jsxsd/xskb/xskb_list.do', headers=header, data=post_data)
        soup = BeautifulSoup(response.text, 'lxml')
        page = soup.find_all('div', attrs={'class': "kbcontent"})

        table = []
        num_list = {
            '0': '第一节',
            '1': '第二节',
            '2': '第三节',
            '3': '第四节',
            '4': '第五节',
            '5': '第六节',
        }
        time_list = {
            '0': '8:15 - 9:55',
            '1': '10:20 - 12:00',
            '2': '14:30 - 16:10',
            '3': '16:20 - 17:50',
            '4': '18:30 - 20:00',
            '5': '20:10 - 21:40'
        }

        n = 0
        for i in range(7):
            column = []
            for j in range(6):
                c = page[i + j * 7]
                if c.string == '\xa0':
                    # column.append([])
                    pass
                else:
                    teacher = c.find('font', attrs={'title': '老师'})
                    classes = c.find('font', attrs={'title': '班级'})
                    weeks = c.find('span', attrs={'title': '选课人数'})
                    classroom = c.find('font', attrs={'title': '上课地点'})
                    if teacher is not None:
                        teacher = teacher.string
                    else:
                        teacher = ''
                    if classes is not None:
                        classes = classes.contents[0]
                    else:
                        classes = ''
                    if weeks is not None:
                        weeks = weeks.contents[2]
                    else:
                        weeks = ''
                    if classroom is not None:
                        classroom = classroom.string
                    else:
                        classroom = '(暂无)'
                    course = {
                        'time': time_list[str(j)],
                        'courseName': c.contents[0],
                        'num': num_list[str(j)],
                        # 'teacher': teacher,
                        # 'classes': classes,
                        # 'weeks': weeks,
                        'className': classroom,
                    }
                    column.append(course)
                n += 1
                # elif '---------------------' in c:  # 一个格子有多门课的
                #     course_counts = str(c.contents).count(
                #         '---------------------') + 1  # 课程数量为分割线数量+1
                #     courses = []  # 这个格子的多门课
                #     for k in range(course_counts):
                #         teacher = c.find('font', attrs={'title': '老师'})
                #         classes = c.find('font', attrs={'title': '班级'})
                #         weeks = c.find('span', attrs={'title': '选课人数'})
                #         classroom = c.find('font', attrs={'title': '上课地点'})
                #         if teacher is not None:
                #             teacher = teacher.string
                #         else:
                #             teacher = ''
                #         if classes is not None:
                #             classes = classes.contents[0]
                #         else:
                #             classes = ''
                #         if weeks is not None:
                #             weeks = weeks.contents[2]
                #         else:
                #             weeks = ''
                #         if classroom is not None:
                #             classroom = classroom.string
                #         else:
                #             classroom = ''
                #
                #         course = {
                #             'name': c.contents[0 + k * 10],
                #             'teacher': teacher,
                #             'classes': classes,
                #             'weeks': weeks,
                #             'classroom': classroom,
                #         }
                #         courses.append(course)
                #     row.append({
                #         'row': i,
                #         'week': j,
                #         'courses': courses
                #     })
            table.append(column)

        return json.dumps({'classtable': table}, ensure_ascii=False)

        # with open('courses.json', 'w', encoding='utf-8')as f:
        #     f.write(json.dumps(table, ensure_ascii=False))
        #     f.close()

    def encode(self):
        with open('./QiangZhi/encode.js', encoding='utf-8') as f:
            js = execjs.compile(f.read())
            return js.call('encode', self.data_str, self.user_name, self.password)

    def first_load(self, uid):
        db.session.query(Classtable).filter(Classtable.userid == uid).delete(synchronize_session=False)
        db.session.commit()

        for i in range(1, 19):  # 默认拉18周课表
            week_data = self.parse_page(i)
            classtable = Classtable(userid=uid, week=i, data=week_data)
            db.session.add(classtable)
        db.session.commit()